import { extend } from 'umi-request'
import notification from '../notification'
import confirm from '../confirm'
import filterURLSearchParams from '../filterURLSearchParams'
import { isEmpty, isNil, has, forEachObjIndexed, clone } from 'ramda'
import isString from '../isString'

function toLine(name: string) {
	return name
		.replace(/([A-Z])/g, '_$1')
		.toLowerCase()
		.trim()
}
const request = extend({
	headers: {
		Accept: '*/*',
		'Content-Type': 'application/json',
	},
	useCache: true,
	ttl: 500,
	paramsSerializer: (params) => {
		const str: string[] = []
		forEachObjIndexed((value: string | Array<any>, key) => {
			if (Array.isArray(value)) {
				value.forEach((res, index) => {
					if (isNil(res)) {
						return
					}
					if (typeof res === 'object') {
						forEachObjIndexed((value2, key2) => {
							if (key === 'orders' && typeof value2 === 'string') {
								value2 = toLine(value2)
							}
							str.push(`${key}[${index}].${String(key2)}=${value2}`)
						}, res)
					} else {
						str.push(`${key}[${index}]=${isString(res) ? res.trim() : res}`)
					}
				})
			} else {
				str.push(`${key}=${isString(value) ? value.trim() : value}`)
			}
		}, params)
		return encodeURI(str.join('&'))
	},
	errorHandler: function (error) {
		let msg = ''
		if (error.response) {
			msg = error.response.statusText
		} else {
			msg = error.message
		}
		return { data: null, msg, code: -1, success: false }
	},
})
request.interceptors.request.use((url, options) => {
	const _options = clone(options)
	if (_options.data instanceof FormData) {
		_options.headers = {
			Accept: '*/*',
		}
	}
	if (_options.method === 'GET' || _options.method === 'get') {
		_options.params = filterURLSearchParams(_options.params as Record<string, any>)
	}
	const Authorization = 'Bearer ' + localStorage.getItem((window as any).AppConfig?.token || 'accessToken')
	const AppUrl = (window as any).AppConfig?.httpPrefix || '/serverApi'
	url = url.startsWith('http') || options.noPrefix || url.startsWith(AppUrl) ? url : `${AppUrl}${url}`
	_options.url = url
	return {
		url,
		options:
			isNil(Authorization) || isEmpty(Authorization) ? _options : Object.assign(_options, { headers: { Authorization } }),
	}
})
export default request
const successCode = ['0X0000', '200', 0]
export function notLogin() {
	localStorage.removeItem('accessToken')
	localStorage.removeItem('userId')
	confirm({
		title: '登录失效，是否跳转登录',
		onOk() {
			history.pushState(
				{
					from: location.pathname,
					search: location.search,
				},
				'登录',
				'/login'
			)
			location.reload()
			// location.href = `/login?url=${location.pathname}`
		},
	})
}
export function updateResponse<T = any, P extends Promise<any> = any>(data: P) {
	return data.then((data: F.AjaxData<T>) => {
		if (has('response', data) && data.response.status === 200) {
			return data
		}
		if (successCode.includes(data.code)) {
			return data
		}
		switch (data.code) {
			case '401':
			case 401:
				notLogin()
				break
			case '200':
			case '0X0000':
				break
			default:
				notification({
					description: data.msg,
					message: '异常',
				})
				data.success = false
				break
		}
		return data
	})
}
